<?php
namespace Home\Controller\Respo;
use Think\Controller;

class IndexController extends Controller
{
    /*
     * function index
     * 仓库展示
     * return array
     */
    public function index()
    {
        if(cookie('username') == null || cookie('pwd') == null){
            return redirect('/drm/');
        }
        $depots = M('depot');
        $data = $depots->select();
        $person['name'] = cookie('username');
        $this->assign('person',$person);
        $this->assign('data',$data);
        $this->display('Respo/list');
    }

    /*
     * function depotAdd
     * 添加仓库
     * return bool
     */
    public function depotAdd()
    {
        if(cookie('username') == null || cookie('pwd') == null){
            return redirect('/drm/');
        }

        if(IS_POST){
            $data['name'] = trim(I('POST.name'));
            $data['use_rate'] = trim(I('POST.use_rate'));
            $data['address'] = trim(I('POST.address'));

            $depots = M('depot');
            $res = $depots->data($data)->add();
            return $this->redirect('Home/Respo/Index/',array(),1,'页面跳转中');
        }
        $person['name'] = cookie('username');
        $this->assign('person',$person);
        $this->assign('type','depotAdd');
        $this->display('Respo/add');
    }

    /*
     * function depotDelete
     * 仓库删除
     * return bool
     */
    public function depotDelete()
    {
        if(cookie('username') == null || cookie('pwd') == null){
            return redirect('/drm/');
        }

        if(!$id = trim(I('POST.id'))){
            return null;
        }
        $depots = M('depot');
        return $depots->where("id = $id")->delete();
    }

    public function depotEdit()
    {
        if(cookie('username') == null || cookie('pwd') == null){
            return redirect('/drm/');
        }

        if(!$id = trim(I('id'))){
            return false;
        }

        $depots = M('depot');
        if(IS_POST){//提交修改
            I('POST.name') && $data['name'] = trim(I('POST.name'));
            I('POST.use_rate') != null && $data['use_rate'] = (float) trim(I('POST.use_rate'));
            I('POST.address') && $data['address'] = trim(I('POST.address'));

            $res = $depots->where("id = $id")->save($data);
            if($res){
                return $this->redirect('Home/Respo/Index/',array(),1,'页面跳转中');
            }else{
                $this->error('没有修改哦,请重试');
            }
        }

        $depot = $depots->where("id = $id")->find();//找到指定仓库
        $person['name'] = cookie('username');
        $this->assign('person',$person);
        $this->assign('type','depotEdit');
        $this->assign('depot',$depot);
        $this->display('Respo/add');
    }
}
